package services

import (
	"encoding/json"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/jinzhu/gorm"
	"go_motor_catalog/util"
	"net/url"
	"strings"
)

const getKymcoCatalogUrl = "https://www.kymco.com.tw/manuals/"

const getInKymcoCatalogUrl = "https://kymco.com.cn/index.php/index/Userinfo/qdjssclist"

const inKymcoBaseUrl = "https://ckmco-video.oss-cn-shanghai.aliyuncs.com/"

type KymcoOm struct {
}

type KymcoOmRes struct {
	ModelName       string
	ModelYear       string
	CatalogUrl      string
	CatalogShareUrl string
	Desc            string
}

func NewKymcoOm() *KymcoOm {
	return &KymcoOm{}
}

func (c *KymcoOm) getOutCatalog() []*KymcoOmRes {
	res := make([]*KymcoOmRes, 0)
	ccSlice := []string{"大型重機", "速克達", "打檔車", "電動車", "微型電動二輪車", "代步車", "其他"}
	for i := range ccSlice {
		modelCode := url.QueryEscape(ccSlice[i])
		geCatalogUrl := getKymcoCatalogUrl + modelCode
		body := util.NewHttpUtil().Post(geCatalogUrl)
		dom, err := goquery.NewDocumentFromResponse(body)
		if err != nil {
			fmt.Println("获取kymco图纸数据失败->", err)
			continue
		}
		dom.Find("tbody").First().Find("tr").Each(func(i int, s *goquery.Selection) {
			modelName := s.Find("td[data-title=手冊名稱]").Find("div").Text()
			modelYear := strings.Split(s.Find("td[data-title=日期]").Find("div").Text(), "/")[0]
			catalogUrl, isExits := s.Find("td[data-title=下載]").Find("a").Attr("href")
			if isExits {
				res = append(res, &KymcoOmRes{
					ModelName:  modelName,
					ModelYear:  modelYear,
					CatalogUrl: catalogUrl,
				})
			}
		})

	}
	return res
}
func (c *KymcoOm) getInCatalog() []*KymcoOmRes {
	res := make([]*KymcoOmRes, 0)
	body := util.NewHttpUtil().Get(getInKymcoCatalogUrl)
	var apiResult map[string]interface{}
	var dataList []map[string]interface{}
	err := json.Unmarshal([]byte(body), &apiResult)
	if err != nil {
		fmt.Println("获取kymco图纸数据失败->", err)
		return res
	}
	dataListStr, err := json.Marshal(apiResult["data"])
	if err != nil {
		fmt.Println("获取kymco图纸数据失败->", err)
		return res
	}
	err = json.Unmarshal([]byte(dataListStr), &dataList)
	if err != nil {
		fmt.Println("获取kymco图纸数据失败->", err)
		return res
	}
	for i := range dataList {
		data := dataList[i]
		res = append(res, &KymcoOmRes{
			ModelName:  fmt.Sprintf("%s", data["title"]),
			ModelYear:  strings.Split(fmt.Sprintf("%s", data["uploadpdf"]), "/")[1],
			CatalogUrl: inKymcoBaseUrl + fmt.Sprintf("%s", data["uploadpdf"]),
		})
	}
	return res
}

func (c *KymcoOm) CrawData(db *gorm.DB) {
	catalogs := c.getOutCatalog()
	catalogs = append(catalogs, c.getInCatalog()...)
	for i := range catalogs {
		catalogInfo := catalogs[i]
		fmt.Printf("%s-%s-%s \n", catalogInfo.ModelName, catalogInfo.ModelYear, catalogInfo.CatalogUrl)
	}
	//modelOmDao := dao.NewManualModelOmDao(db)
	//catalogOmDao := dao.NewManualCatalogOmDao(db)
	//for i := range catalogs {
	//	param := catalogs[i]
	//	modelParam := &dao.ManualModelOm{
	//		ModelName: param.ModelName,
	//		ModelYear: param.ModelYear,
	//		BrandId:   8,
	//	}
	//	catalogParam := &dao.ManualCatalogOm{
	//		CatalogUrl:  param.CatalogUrl,
	//		CatalogDesc: "",
	//	}
	//	modelId := modelOmDao.CreateManualModelOm(modelParam)
	//	catalogParam.ModelId = modelId
	//	catalogOmDao.CreateManualCatalogOm(catalogParam)
	//	fmt.Println(param.ModelName, "-", param.ModelYear, "-successfull")
	//}
	fmt.Print("all successfull")
}
